<template>
  <div class="list-common-tab">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-input
          v-model="search"
          placeholder="请输入检索内容"
          @keyup.enter="handleSearch"
          input-style="padding-right:30px"
        ></el-input>
      </el-col>
      <el-col :span="8" class="operation-container">
        <el-button type="info" @click="handleSearch">检索</el-button>
        <el-button type="info" @click="handleClear">清空</el-button>
        <el-button type="primary" @click="selectPartTimeDept">选择兼职部门</el-button>
      </el-col>
    </el-row>
    <div class="star-table-container">
      <el-table
        :data="userList"
        :stripe="stripe"
      >
      <el-table-column type="index" width="50" />
        <el-table-column prop="orgName" label="部门名称" />
        <el-table-column label="是否主部门" align="center">
          <template #default="scope">
            {{ scope.row.isMain === 1 ? '是' : "否"}}
          </template>
        </el-table-column>
        <el-table-column prop="op" align="center" label="操作" width="200">
          <template #default="scope">
            <el-popconfirm :title="showMainContent(scope)" width="300" @confirm="setMainDept(scope)" v-if="scope.row.isMain===0">
              <template #reference>
                <el-button type="primary">设为主部门</el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm :title="showContent(scope)" width="300" @confirm="handleRemoveUser(scope)">
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="star-table-pagination">
      <el-pagination
        background
        :total="listTotal"
        :layout="pageOperate"
        :default-page-size="size"
        :page-sizes="listPageSizes"
        v-model:page-size="pageSize"
        @size-change="handleSizeChange"
        v-model:current-page="currentPage"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <el-dialog
      center
      draggable
      title="部门选择"
      destroy-on-close
      v-model="visibleForm"
      :close-on-click-modal="false"
    >
    <UserSelect :range="range" :tags="tags" :isEcho="false"  @close-dialog="closeDialog" ref="userSelectRef" :selected="selected" @reload-data="reloadData" @commit-selected="saveSelectedDept"/>
  </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { ref, onMounted, watch, computed } from 'vue'
import { stripe, size, pageOperate, listPageSizes } from '@/config/list'
import { loadUserByRoleId, deleteUser, getRoleSelectedUser, putPartTimeDept, loadUserPartTimeDept } from '@/api/system/user/UserManager'
import { saveGrant, deleteData } from '@/api/system/privilege/GrantManager'
import { GrantType, GrantTargetType } from '@/model/system/privilege/GrantModel'
import UserSelect from '@/components/common/select/UserSelect.vue'

import '@/style/list.less'

const search = ref('')
const userId = ref('')
const userList = ref([])
const listTotal = ref(0)
const pageSize = ref(size)
const currentPage = ref(1)
const visibleForm = ref(false)
const emit = defineEmits(['change-data'])
const props = defineProps({ fid: String })
const selected = ref([])
const userSelectRef = ref()
const range = ref(['unit'])
const tags = ref(['dept'])

const handleSearch = () => {
  currentPage.value = 1
  loadListData()
}

const handleClear = () => {
  currentPage.value = 1
  search.value = ''
  loadListData()
}

const saveSelectedDept = (deptList) => {
  const uid = props.fid
  let deptIds = ''
  deptList.map((item, index) => {
    console.log(item)
    deptIds += item.id + ','
    return deptIds
  })
  if (deptIds.length > 0) {
    deptIds = deptIds.substring(0, deptIds.length - 1)
  }
  putPartTimeDept(uid, deptIds, '0').then(() => {
    closeDialog()
    ElMessage.success('保存成功。')
    reloadData()
  }).catch(error => {
    ElMessage.error(error.message)
  })
}

const handleRemoveUser = (scope) => {
  deleteData(scope.row.id, props.fid).then(() => {
    ElMessage({
      message: '删除成功!',
      type: 'success',
      duration: 800
    })
    reloadData()
  }).catch(error => {
    ElMessage.error(error.message)
  })
}

/**
 * 设为主部门
 * @param {*} scope
 */
const setMainDept = (scope) => {
  const uid = props.fid
  putPartTimeDept(uid, scope.row.orgId, '1').then(() => {
    closeDialog()
    ElMessage.success('设置成功。')
    reloadData()
  }).catch(error => {
    ElMessage.error(error.message)
  })
}

const handleCreateUser = () => {
  userId.value = ''
  visibleForm.value = true
}

const closeDialog = () => {
  visibleForm.value = false
}

const selectPartTimeDept = () => {
  getRoleSelectedUser(props.fid).then(data => {
    // selected.value = data.map(item => {
    //   return item.targetId
    // })
    selected.value = data
    visibleForm.value = true
  })
}

const reloadData = () => {
  loadListData()
  emit('change-data')
}

const showContent = computed(() => (scope) => {
  return `是否要删除${scope.row.orgName}？`
})

const showMainContent = computed(() => (scope) => {
  return `是否将${scope.row.orgName}设为主部门？`
})

const loadListData = () => {
  console.log('@@@@@', props.fid)
  loadUserPartTimeDept({
    fid: props.fid,
    current: currentPage.value,
    pageSize: pageSize.value,
    search: search.value
  }).then(data => {
    const { total, list } = data
    listTotal.value = total
    userList.value = list
  })
}

const handleSizeChange = () => {
  loadListData()
}

const handleCurrentChange = () => {
  loadListData()
}

watch(
  () => props.fid,
  () => {
    currentPage.value = 1
    search.value = ''
    loadListData()
  }
)

onMounted(() => {
  loadListData()
})
</script>
